package com.rslai.base.tool.servertest.intercept;

import com.rslai.base.tool.servertest.command.CallStepCommand;
import com.rslai.base.tool.servertest.command.StepCommand;
import com.rslai.base.tool.servertest.context.Context;
import com.rslai.base.tool.servertest.response.HttpResponse;
import com.rslai.base.tool.servertest.response.Response;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.CharSetUtils;
import org.apache.commons.lang.StringUtils;

public class HttpCallBackInterceptor implements StepCommandInterceptor {
    static final Pattern pattern = Pattern.compile("^[\\s]*([a-zA-Z_]{1}[\\w\\.]*)?\\('?(.*)'?\\)[\\s]*;?[\\s]*$");

    public Object beforeExecute(StepCommand command, Response param, Context context) {
        return param;
    }

    public Object afterExecute(StepCommand command, Response response, Context context) {
        if (!(command instanceof CallStepCommand)) {
            return response;
        }

        if ((response != null) && ((response instanceof HttpResponse)) &&
                (response.getBody() != null) && ((response.getBody() instanceof String))) {
            String body = StringUtils.trim((String) response.getBody());
            body = CharSetUtils.delete(body, "\r\t\n");
            String callbackFunctionName = getCallbackFunctionName(body);
            String realBody = getRealBodyWithoutCallbackName(body);
            if (noCallback(body, realBody)) {
                return response;
            }
            ((HttpResponse) response).setCallback(callbackFunctionName);
            response.setBody(realBody);
        }

        return response;
    }

    private boolean noCallback(String body, String realBody) {
        return body.equals(realBody);
    }

    private String getRealBodyWithoutCallbackName(String body) {
        Matcher matcher = pattern.matcher(body);
        if (matcher.find()) {
            return matcher.group(2);
        }
        return body;
    }

    private String getCallbackFunctionName(String body) {
        Matcher matcher = pattern.matcher(body);
        if (matcher.find()) {
            String name = matcher.group(1);
            if (!"".equals(name)) {
                return name;
            }
        }
        return null;
    }
}
